package org.libermundi.theorcs.chronicles.tapestry.pages.perso;

import java.util.List;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.ValueEncoderFactory;
import org.libermundi.theorcs.chronicles.dto.ChronicleSettings;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.chronicles.services.PersonaManager;
import org.libermundi.theorcs.chronicles.tapestry.base.ChroniclePage;
import org.libermundi.theorcs.chronicles.tapestry.pages.Index;
import org.libermundi.theorcs.core.tapestry.util.GenericSelectModel;
import org.libermundi.theorcs.security.services.SecurityManager;

public class Switch extends ChroniclePage {
	public static final String PAGE_ID="chronicles.pages.perso.switch";
	
	@Inject
	private PersonaManager _personaManager;
	
	@Inject
	private ValueEncoderFactory<Persona> _genericValueEncoderFactory;
	
	@SessionState
	private ChronicleSettings _chronicleSettings;
	
	@Inject
	private SecurityManager _securityManager;
	
	@Property
	private Persona _selectedPerso;

	/* (non-Javadoc)
	 * @see org.libermundi.theorcs.core.tapestry.base.BasePage#getPageId()
	 */
	@Override
	public String getPageId() {
		return PAGE_ID;
	}
	
	@OnEvent("success")
	public Class<?> persoSwitched() {
		_chronicleSettings.setPersona(_selectedPerso);
		return Index.class;
	}
	
	public SelectModel getPersoModel() {
		List<Persona> values = _personaManager.getAllPersona(_securityManager.getCurrentUser(), _chronicleSettings.getChronicle());
			values.remove(_chronicleSettings.getPersona()); // Cannot select the current Persona	
		return new GenericSelectModel<>(values);
	}
	
	public ValueEncoder<Persona> getPersoEncoder() {
		return _genericValueEncoderFactory.create(Persona.class);
	}	
}
